<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn('mul')">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn('mul')">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist>
        自定义分级报警管理
      </template>
    </list_controller>
    <!-- 新增弹框 -->
      <vxe-modal esc-closable destroy-on-close :lock-view="false" :width="660" :height="auto" v-model="state.addModal"
        resize :mask="true" showFooter>
        <template #title>
          <div class="w100 h100 fsc mask_title">{{state.modalTitle}}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="top">
              <el-row :gutter="20">
                <el-col :span="24">
                  <p class="mask_sub_title">
                    <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span>传感器信息</span>
                    <el-popover placement="top" :width="400" trigger="hover">
                      <template #reference>
                        <svg-icon style="margin-left:10px;" class-name="search-icon" icon-class="tishi" />
                      </template>
                      <span style="color:rgba(230, 162, 60, 1)">
                        测点的当前值大于或等于预报值后与该测点在前一天的平均值相比，如涨幅大于设定范围并且该情况出现次数等于或超过设定次数后，触发分级报警，报警等级由用户选择!
                      </span>
                    </el-popover>
                  </p>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="设备名称" prop="deviceName">
                    <el-select clearable filterable v-model="state.formData.deviceName" placeholder="请选择"
                      @change="stationModelChange">
                      <el-option v-for="item in state.stationmodelList" :key="item.name" :label="item.name"
                        :value="item.name">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="测点编号" prop="pointCode">
                    <el-select clearable filterable v-model="state.formData.pointCode" placeholder="请选择"
                      @change="pointModelChange">
                      <el-option v-for="item in state.stationInNumList" :key="item.code" :label="item.code"
                        :value="item.code">
                        <span>{{ item.code+'-'+item.place }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安装位置" prop="place">
                    <el-input disabled v-model="state.formData.place" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="报警等级" prop="alarmLevel">
                    <el-select clearable filterable v-model="state.formData.alarmLevel" placeholder="请选择">
                      <el-option v-for="item in 4" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="`预报值(${state.formData.unit})`" prop="forecastValue">
                    <el-input v-model="state.formData.forecastValue" oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1')  .replace(/(\.\d{2})\d*/, '$1')" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="涨幅(%)" prop="increaseRate">
                    <el-input v-model="state.formData.increaseRate" oninput="value =value.replace(/[^\-\d.]/g, '') .replace(/^\./g, '').replace(/\.{2,}/g,
'.').replace(/(\.\d+)\./g, '$1') .replace(/(-)\./g, '$1') .replace(/\-{2,}/g, '-')
.replace(/(\d+|\.)-/g, '$1') .replace(/-(0){2,}/g,'$1') .replace(/(-)0+(\d+)/g, '$1$2')
.replace(/^0+(\d)/, '$1')  .replace(/(\.\d{2})\d*/, '$1')" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="出现次数" prop="occurCount">
                    <el-select clearable filterable v-model="state.formData.occurCount" placeholder="请选择">
                      <el-option v-for="item in [1,2,3,4,5,10]" :key="item" :label="item" :value="item">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input type="textarea" v-model="state.formData.remark" placeholder="请输入"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </template>
      </vxe-modal>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    reactive
  } from "vue";
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    table_headers
  } from '@/components/commonCom/table_headers';
  import axios from "@/utils/request"
  import usePagesStore from '@/store/modules/pages'
  import {
    getlistSensorPoints
  } from '@/api/config'
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore()
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP
  components: {
    list_controller
  }
  const upload = ref(null)
  let state = reactive({
    options: {
      tableheads: computed(() => table_headers.configGrade),
      queryList: {
        dropdownUrl: '',
        querys: [],
        queryMap: new Map([
          ['sensorTypeId', 'safety_pointType'],
          ['deviceTypeId', 'safety_deviceType'],
          ['alarmTypeId', 'alarmType']
        ])
      },
      dataUrl: '/grade/list',
      delUrl: '/grade/del',
      addUrl: '/grade/add',
      descUrl: '/grade/getById',
      editUrl: '/grade/modify',
    },
    // 表单
    addModal: false,
    modalTitle: '新增分级报警',
    formRef: null,
    formData: {
      unit: ''
    },
    rules: {
      deviceName: [{
        required: true,
        message: '请选择设备名称',
        trigger: 'change'
      }],
      pointCode: [{
        required: true,
        message: '请选择测点编号',
        trigger: 'change'
      }],
      place: [{
        required: true,
        message: '请输入地点',
        trigger: 'blur'
      }],
      alarmLevel: [{
        required: true,
        message: '请选择报警等级',
        trigger: 'change'
      }],
      forecastValue: [{
        required: true,
        message: '请输入预报值',
        trigger: 'blur'
      }],
      increaseRate: [{
        required: true,
        message: '请输入涨幅',
        trigger: 'blur'
      }],
      occurCount: [{
        required: true,
        message: '请选择出现次数',
        trigger: 'change'
      }],
    },
    editId: undefined,
    stationmodelList: [],
    stationInNumList: [],

  })
  // 新增按钮
  function addBtn(row) {
    state.modalTitle = '新增分级报警'
    state.addModal = true
    state.formData = {
      unit: ''
    }
    state.editId = undefined
  }
  // 编辑按钮
  function editBtn(row) {
    state.modalTitle = '编辑分级报警'
    state.addModal = true
    axios.post(state.options.descUrl, {
      id: row.id
    }).then(res => {
      if (res.code == 200) {
        state.stationmodelList.forEach(item => {
          if (res.data.deviceName == item.name) {
            state.stationInNumList = item.children
          }
        })
        state.formData = res.data
        state.editId = res.data.id
      }
    })
  }

  function deleteBtn(row) {
    let ids = []
    if (row != 'mul') {
      ids = [row.id]
    } else {
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        proxy.$modal.msgSuccess('请先勾选所要删除数据!');
      }
    }
    if (ids.length > 0) {
      ElMessageBox.confirm(
          '确定要删除该数据吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        .then(() => {
          axios.post(state.options.delUrl, ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              ElMessage({
                type: 'success',
                message: res.msg,
              })
              store.records = []
            }
          })

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '删除取消',
          })
        })
    }

  }
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["formRef"].validate(valid => {
      if (valid) {
        if (state.editId) {
          state.formData.id = state.editId
          axios.post(state.options.editUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        } else {
          axios.post(state.options.addUrl, state.formData).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              state.addModal = false
              proxy.$modal.msgSuccess(res.msg);
            }
          })
        }
      }
    })
  }

  function cancel() {
    state.addModal = false
  }

  function getsubstationmodelList() {
    getlistSensorPoints({}).then(res => {
      state.stationmodelList = res.data
    })
  }

  function stationModelChange(val) {
    state.stationmodelList.forEach(item => {
      if (val == item.name) {
        state.stationInNumList = item.children
      }
    })
  }

  function pointModelChange(val) {
    if (val) {
      state.stationInNumList.forEach(item => {
        if (val == item.code) {
          state.formData.unit = item.unit
          state.formData.place = item.place
        }
      })
    } else {
      state.formData.place = undefined
    }
  }
  getsubstationmodelList()
</script>
<style scoped>
  :deep(.el-popper.is-customized) {
    padding: 6px 12px;
    background: rgba(230, 162, 60, .06) !important;

  }
</style>